/*
 * CargaArchivosPage.java
 *
 * Created on August 16, 2007, 9:55 AM
 * Copyright FSanchez
 */
package consultasmanualviaweb;

import com.computec.manualesweb.dto.AplicacionesDto;
import com.computec.manualesweb.dto.VersionDto;
import com.computec.manualesweb.exception.ManualWebException;
import com.computec.manualesweb.source.ManualesWebSource;
import com.sun.rave.web.ui.appbase.AbstractPageBean;
import com.computec.manualesweb.delegate.ManualWebDelegate;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import javax.faces.FacesException;
import com.sun.rave.web.ui.component.Form;
import com.sun.rave.web.ui.component.ThemeLinks;
import javax.faces.component.html.HtmlPanelGrid;
import javax.faces.component.html.HtmlOutputText;
import javax.faces.component.html.HtmlSelectOneMenu;
import com.sun.jsfcl.data.DefaultSelectItemsArray;
import javax.faces.component.UISelectItems;
import com.sun.rave.web.ui.component.DropDown;
import com.sun.rave.web.ui.model.SingleSelectOptionsList;
import com.sun.rave.web.ui.component.TextArea;
import javax.faces.component.html.HtmlCommandButton;
import javax.faces.component.html.HtmlInputHidden;
import javax.faces.component.html.HtmlForm;
import com.sun.rave.web.ui.component.Alert;
import javax.portlet.PortletRequest;
import com.sun.rave.web.ui.component.PageAlert;


public class CargaArchivosPage extends AbstractPageBean {
    // <editor-fold defaultstate="collapsed" desc="Creator-managed Component Definition">
    
    private int __placeholder;
    
    private ThemeLinks themeLinks1 = new ThemeLinks();
    
    public ThemeLinks getThemeLinks1() {
	return themeLinks1;
    }
    
    public void setThemeLinks1(ThemeLinks t) {
	this.themeLinks1 = t;
    }
    
    private Form formCargar = new Form();
    
    public Form getFormCargar() {
	return formCargar;
    }
    
    public void setFormCargar(Form f) {
	this.formCargar = f;
    }

    private HtmlPanelGrid gridPanelContainer = new HtmlPanelGrid();

    public HtmlPanelGrid getGridPanelContainer() {
        return gridPanelContainer;
    }

    public void setGridPanelContainer(HtmlPanelGrid hpg) {
        this.gridPanelContainer = hpg;
    }

    private HtmlPanelGrid gridPanelTop = new HtmlPanelGrid();

    public HtmlPanelGrid getGridPanelTop() {
        return gridPanelTop;
    }

    public void setGridPanelTop(HtmlPanelGrid hpg) {
        this.gridPanelTop = hpg;
    }

    private HtmlPanelGrid gridPanelBottom = new HtmlPanelGrid();

    public HtmlPanelGrid getGridPanelBottom() {
        return gridPanelBottom;
    }

    public void setGridPanelBottom(HtmlPanelGrid hpg) {
        this.gridPanelBottom = hpg;
    }

    private HtmlOutputText outputText1 = new HtmlOutputText();

    public HtmlOutputText getOutputText1() {
        return outputText1;
    }

    public void setOutputText1(HtmlOutputText hot) {
        this.outputText1 = hot;
    }

    private DropDown dropDownApp = new DropDown();

    public DropDown getDropDownApp() {
        return dropDownApp;
    }

    public void setDropDownApp(DropDown dd) {
        this.dropDownApp = dd;
    }

    private DropDown dropDownVersiones = new DropDown();

    public DropDown getDropDownVersiones() {
        return dropDownVersiones;
    }

    public void setDropDownVersiones(DropDown dd) {
        this.dropDownVersiones = dd;
    }

    private HtmlOutputText outputText2 = new HtmlOutputText();

    public HtmlOutputText getOutputText2() {
        return outputText2;
    }

    public void setOutputText2(HtmlOutputText hot) {
        this.outputText2 = hot;
    }

    private HtmlOutputText outputTextDesc = new HtmlOutputText();

    public HtmlOutputText getOutputTextDesc() {
        return outputTextDesc;
    }

    public void setOutputTextDesc(HtmlOutputText hot) {
        this.outputTextDesc = hot;
    }

    private TextArea textAreaDesc = new TextArea();

    public TextArea getTextAreaDesc() {
        return textAreaDesc;
    }

    public void setTextAreaDesc(TextArea ta) {
        this.textAreaDesc = ta;
    }

    private HtmlCommandButton buttonCargar = new HtmlCommandButton();

    public HtmlCommandButton getButtonCargar() {
        return buttonCargar;
    }

    public void setButtonCargar(HtmlCommandButton hcb) {
        this.buttonCargar = hcb;
    }

    private HtmlCommandButton buttonVolver = new HtmlCommandButton();

    public HtmlCommandButton getButtonVolver() {
        return buttonVolver;
    }

    public void setButtonVolver(HtmlCommandButton hcb) {
        this.buttonVolver = hcb;
    }

    private HtmlInputHidden hiddenField1 = new HtmlInputHidden();

    public HtmlInputHidden getHiddenField1() {
        return hiddenField1;
    }

    public void setHiddenField1(HtmlInputHidden hih) {
        this.hiddenField1 = hih;
    }

    private Form formFileUpload = new Form();

    public Form getFormFileUpload() {
        return formFileUpload;
    }

    public void setFormFileUpload(Form f) {
        this.formFileUpload = f;
    }

    private HtmlPanelGrid gridPanel1 = new HtmlPanelGrid();

    public HtmlPanelGrid getGridPanel1() {
        return gridPanel1;
    }

    public void setGridPanel1(HtmlPanelGrid hpg) {
        this.gridPanel1 = hpg;
    }

    private Alert alertMessage = new Alert();

    public Alert getAlertMessage() {
        return alertMessage;
    }

    public void setAlertMessage(Alert a) {
        this.alertMessage = a;
    }

    private HtmlCommandButton buttonModificar = new HtmlCommandButton();

    public HtmlCommandButton getButtonModificar() {
        return buttonModificar;
    }

    public void setButtonModificar(HtmlCommandButton hcb) {
        this.buttonModificar = hcb;
    }
    
    // </editor-fold>

	
    
    
    public CargaArchivosPage() {

	// <editor-fold defaultstate="collapsed" desc="Creator-managed Component Initialization">
	try {
	} catch (Exception e) {
	    log("Page1 Initialization Failure", e);
	    throw e instanceof javax.faces.FacesException ? (FacesException) e: new FacesException(e);
	}
	// </editor-fold>
	// TODO: Add your own initialization code here (optional)
    }

    /** 
     * <p>Return a reference to the scoped data bean.</p>
     */
    protected SessionManualesViaWebBean getSessionManualesViaWebBean() {
        return (SessionManualesViaWebBean)getBean("SessionManualesViaWebBean");
    }


    /** 
     * <p>Return a reference to the scoped data bean.</p>
     */
    protected RequestManualesViaWebBean getRequestManualesViaWebBean() {
        return (RequestManualesViaWebBean)getBean("RequestManualesViaWebBean");
    }


    /** 
     * <p>Return a reference to the scoped data bean.</p>
     */
    protected ApplicationManualesViaWebBean getApplicationManualesViaWebBean() {
        return (ApplicationManualesViaWebBean)getBean("ApplicationManualesViaWebBean");
    }


    /** 
     * <p>Callback method that is called whenever a page is navigated to,
     * either directly via a URL, or indirectly via page navigation.
     * Customize this method to acquire resources that will be needed
     * for event handlers and lifecycle methods, whether or not this
     * page is performing post back processing.</p>
     * 
     * <p>Note that, if the current request is a postback, the property
     * values of the components do <strong>not</strong> represent any
     * values submitted with this request.  Instead, they represent the
     * property values that were saved for this view when it was rendered.</p>
     */
    public void init() {
        // Perform initializations inherited from our superclass
        super.init();
        // Perform application initialization that must complete
        // *before* managed components are initialized
        // TODO - add your own initialiation code here

        // <editor-fold defaultstate="collapsed" desc="Creator-managed Component Initialization">
        // Initialize automatically managed components
        // *Note* - this logic should NOT be modified
        try {
            _init();
        } catch (Exception e) {
            log("CargaArchivosPage Initialization Failure", e);
            throw e instanceof FacesException ? (FacesException) e: new FacesException(e);
        }
        // </editor-fold>
        // Perform application initialization that must complete
        // *after* managed components are initialized
        // TODO - add your own initialization code here
	Object o = this.getFacesContext().getExternalContext().getRequest();
        if(o instanceof PortletRequest ){
            PortletRequest req = (PortletRequest)o;
          
	     String[] directorio_= (String[]) req.getParameterValues("directorio");
	    req.removeAttribute("directorio");
	    
	    String directorioCompleto_ = "";
            if (directorio_!=null){                
                for(int i =0; i<directorio_.length;i++){
                    if(i<directorio_.length-1){
                        directorioCompleto_+=directorio_[i]+File.separator;
                    } else{
                        directorioCompleto_+=directorio_[i];
                    }
                }
	    }
	    String serverFileName = (String) req.getParameter("serverFileName");
	    req.removeAttribute("serverFileName");
	    File serverFile=null;
	    if(!directorioCompleto_.equals("") && serverFileName!=null){
		serverFile = new File(directorioCompleto_, serverFileName);
	    }
	    if(serverFile!=null && serverFile.canRead()){
		System.out.println("LDAP USER:"+this.getSessionManualesViaWebBean().getLdapUser()); 
		System.out.println("ARCHIVO:"+serverFileName); 
		this.getSessionManualesViaWebBean().setUploadedFile(serverFile, this.getSessionManualesViaWebBean().getLdapUser());
	    }
        }

    }

    /** 
     * <p>Callback method that is called after the component tree has been
     * restored, but before any event processing takes place.  This method
     * will <strong>only</strong> be called on a postback request that
     * is processing a form submit.  Customize this method to allocate
     * resources that will be required in your event handlers.</p>
     */
    public void preprocess() {
    }

    /** 
     * <p>Callback method that is called just before rendering takes place.
     * This method will <strong>only</strong> be called for the page that
     * will actually be rendered (and not, for example, on a page that
     * handled a postback and then navigated to a different page).  Customize
     * this method to allocate resources that will be required for rendering
     * this page.</p>
     */
    public void prerender() {
    }

    /** 
     * <p>Callback method that is called after rendering is completed for
     * this request, if <code>init()</code> was called (regardless of whether
     * or not this was the page that was actually rendered).  Customize this
     * method to release resources acquired in the <code>init()</code>,
     * <code>preprocess()</code>, or <code>prerender()</code> methods (or
     * acquired during execution of an event handler).</p>
     */
    public void destroy() {
    }

    /** 
     * <p>Automatically managed component initialization.  <strong>WARNING:</strong>
     * This method is automatically generated, so any user-specified code inserted
     * here is subject to being replaced.</p>
     */
    private void _init() throws Exception {
    }


    public void buttonCargar_action() {
	this.getSessionManualesViaWebBean().setRenderedAlert(false);
	this.getSessionManualesViaWebBean().setRenderedModificarButton(false);
        String aplicacionSelected = (String)this.dropDownApp.getValue();
        String versionSelected = (String)this.dropDownVersiones.getValue();
        String descripcion=(String)this.textAreaDesc.getValue();
	String hiddenPath=(String)this.hiddenField1.getValue();
	
	if(aplicacionSelected.equals("") || aplicacionSelected.equals("Seleccione...")){
	    this.getSessionManualesViaWebBean().setRenderedAlert(true);		
	    this.setMensajeAlert("warning", "Advertencia", ManualesWebSource.getInstance().getManualesWebErrorSetupKey("WarningAppNoSeleccionada"), true);
	    return;
	}
	if(versionSelected.equals("") || versionSelected.equals("Seleccione...")){
	    this.getSessionManualesViaWebBean().setRenderedAlert(true);		
	    this.setMensajeAlert("warning", "Advertencia", ManualesWebSource.getInstance().getManualesWebErrorSetupKey("WarningVersionNoSeleccionda"), true);
	    return;
	}
	if( descripcion==null || descripcion.trim().equals("") ){
	    this.getSessionManualesViaWebBean().setRenderedAlert(true);		
	    this.setMensajeAlert("warning", "Advertencia", ManualesWebSource.getInstance().getManualesWebErrorSetupKey("WarningNoDescripcion"), true);
	    return;
	}else if(descripcion.length()>120){
	    this.getSessionManualesViaWebBean().setRenderedAlert(true);		
	    this.setMensajeAlert("warning", "Advertencia", ManualesWebSource.getInstance().getManualesWebErrorSetupKey("WarningDescripcionLength"), true);
	    return;
	}
	
	File manualFile_=this.getSessionManualesViaWebBean().getUploadedFile(this.getSessionManualesViaWebBean().getLdapUser());
	if(manualFile_!=null){
	    String pathFile_= manualFile_.getAbsolutePath();
	
	    ManualWebDelegate delegate =new ManualWebDelegate();
	    AplicacionesDto dto_=(AplicacionesDto)this.getSessionManualesViaWebBean().getHashAplicaciones().get(aplicacionSelected);
	    VersionDto verDto_=(VersionDto)this.getSessionManualesViaWebBean().getHashVersiones().get(versionSelected);
	    String nombreAplicacion_=dto_.getAplicacion()+"-"+dto_.getSubAplicacion()+"-"+verDto_.getNombreVersion();

	    String extension_=pathFile_.substring(pathFile_.length()-3, pathFile_.length());


		File newFile_=new File(manualFile_.getParentFile().getAbsolutePath(), nombreAplicacion_+"."+extension_);
		boolean existe_=newFile_.exists();
		
		
	    try{		
		    String relativePath_=ManualesWebSource.getInstance().getManualesWebSetupKey("pathArchivosManuales")+"/"+newFile_.getName();  
		    delegate.insertarManual(aplicacionSelected, versionSelected,dto_.getAplicacion()+"-"+dto_.getSubAplicacion(), descripcion, relativePath_);
		    if(existe_){
			newFile_.delete();
		    }
		    boolean renombro_=manualFile_.renameTo(newFile_);	
		    if(renombro_){
			this.setMensajeAlert("success", "Exito", ManualesWebSource.getInstance().getManualesWebSetupKey("SuccessManualUpload"), true);	    
			this.getSessionManualesViaWebBean().setRenderedAlert(true);
			this.getSessionManualesViaWebBean().setUploadedFile(null,this.getSessionManualesViaWebBean().getLdapUser());
			this.limpiarCampos();
			
			this.getSessionManualesViaWebBean().setListManuales(null);
			this.getSessionManualesViaWebBean().setRenderedTabla(true);
		    }else{
			this.getSessionManualesViaWebBean().setRenderedAlert(true);			
			this.setMensajeAlert("warning", "Advertencia", ManualesWebSource.getInstance().getManualesWebErrorSetupKey("WarningRenombrar"), true);	    
		    }
		
	    }catch(ManualWebException ex){		    
		if(manualFile_.exists()){
		    this.getSessionManualesViaWebBean().getFail().add(manualFile_);
		}
		this.getSessionManualesViaWebBean().setRenderedAlert(true);
		this.getSessionManualesViaWebBean().setRenderedModificarButton(true);
		this.setMensajeAlert("warning", "Advertencia", ManualesWebSource.getInstance().getManualesWebErrorSetupKey("WarningManualExisteBD"), true);	    

		ex.printStackTrace();	    
	    }
	}else{
	 
	    this.getSessionManualesViaWebBean().setRenderedAlert(true);		
	    this.setMensajeAlert("warning", "Advertencia", ManualesWebSource.getInstance().getManualesWebErrorSetupKey("WarningArchivoNoCargado"), true);
	}
  
    }
    
    public void setMensajeAlert(String type, String summary, String detail, boolean visible) 
    {
        if (visible){
            this.alertMessage.setType(type);
            this.alertMessage.setSummary(summary);
            this.alertMessage.setDetail(detail);
            this.alertMessage.setVisible(visible);
        }else{
            this.alertMessage.setVisible(visible);
        }
    }


    public void buttonModificar_action() {
       this.getSessionManualesViaWebBean().setRenderedAlert(false);
	 this.getSessionManualesViaWebBean().setRenderedModificarButton(false);
        String aplicacionSelected = (String)this.dropDownApp.getValue();
        String versionSelected = (String)this.dropDownVersiones.getValue();
        String descripcion=(String)this.textAreaDesc.getValue();
	String hiddenPath=(String)this.hiddenField1.getValue();
	
	if(aplicacionSelected.equals("") || aplicacionSelected.equals("Seleccione...")){
	    this.getSessionManualesViaWebBean().setRenderedAlert(true);		
	    this.setMensajeAlert("warning", "Advertencia", ManualesWebSource.getInstance().getManualesWebErrorSetupKey("WarningAppNoSeleccionada"), true);
	    return;
	}
	if(versionSelected.equals("") || versionSelected.equals("Seleccione...")){
	    this.getSessionManualesViaWebBean().setRenderedAlert(true);		
	    this.setMensajeAlert("warning", "Advertencia", ManualesWebSource.getInstance().getManualesWebErrorSetupKey("WarningVersionNoSeleccionda"), true);
	    return;
	}
	if( descripcion==null || descripcion.trim().equals("") ){
	    this.getSessionManualesViaWebBean().setRenderedAlert(true);		
	    this.setMensajeAlert("warning", "Advertencia", ManualesWebSource.getInstance().getManualesWebErrorSetupKey("WarningNoDescripcion"), true);
	    return;
	}
	
	File manualFile_=this.getSessionManualesViaWebBean().getUploadedFile(this.getSessionManualesViaWebBean().getLdapUser());
	if(manualFile_!=null){
	    String pathFile_= manualFile_.getAbsolutePath();

	    ManualWebDelegate delegate =new ManualWebDelegate();
	    AplicacionesDto dto_=(AplicacionesDto)this.getSessionManualesViaWebBean().getHashAplicaciones().get(aplicacionSelected);
	    VersionDto verDto_=(VersionDto)this.getSessionManualesViaWebBean().getHashVersiones().get(versionSelected);
	    String nombreAplicacion_=dto_.getAplicacion()+"-"+dto_.getSubAplicacion()+"-"+verDto_.getNombreVersion();


	    String extension_=pathFile_.substring(pathFile_.length()-3, pathFile_.length());
	    File newFile_=new File(manualFile_.getParentFile().getAbsolutePath(), nombreAplicacion_+"."+extension_);


	    if(newFile_.exists()){		
		newFile_.delete();
	    }
	    boolean b_=manualFile_.renameTo(newFile_);	
	    String relativePath_=ManualesWebSource.getInstance().getManualesWebSetupKey("pathArchivosManuales")+"/"+newFile_.getName();  
	    try{
		if(b_){
		    delegate.updateManual(aplicacionSelected, versionSelected,dto_.getAplicacion()+"-"+dto_.getSubAplicacion(), descripcion, relativePath_);
		    this.setMensajeAlert("success", "Exito", ManualesWebSource.getInstance().getManualesWebSetupKey("SuccessManualUpload"), true);	    
		    this.getSessionManualesViaWebBean().setRenderedAlert(true);
		    this.getSessionManualesViaWebBean().setUploadedFile(null,this.getSessionManualesViaWebBean().getLdapUser());
		    this.limpiarCampos();
		    
		    this.getSessionManualesViaWebBean().setListManuales(null);
		    this.getSessionManualesViaWebBean().setRenderedTabla(true);
		}else{		
		     if(manualFile_.exists()){
		         //System.out.println("ERROR:"+manualFile_.getAbsolutePath()+"-"+manualFile_.exists());
			this.getSessionManualesViaWebBean().getFail().add(manualFile_);
		    }
		    this.getSessionManualesViaWebBean().setRenderedAlert(true);
		    this.getSessionManualesViaWebBean().setRenderedModificarButton(false);
		    this.setMensajeAlert("error", "Error", ManualesWebSource.getInstance().getManualesWebErrorSetupKey("ErrorSistema"), true);	    

		}
	    }catch(ManualWebException ex){		    
		this.getSessionManualesViaWebBean().setUploadedFile(null,this.getSessionManualesViaWebBean().getLdapUser());	    
		if(manualFile_.exists()){
		    this.getSessionManualesViaWebBean().getFail().add(manualFile_);
		}
		this.getSessionManualesViaWebBean().setRenderedAlert(true);

		this.setMensajeAlert("error", "Error", ManualesWebSource.getInstance().getManualesWebErrorSetupKey("ErrorSistema"), true);	    

		ex.printStackTrace();	    
	    }
	}else{
	    
	    this.getSessionManualesViaWebBean().setRenderedAlert(true);		
	    this.setMensajeAlert("warning", "Advertencia", ManualesWebSource.getInstance().getManualesWebErrorSetupKey("WarningArchivoNoCargado"), true);
	}
    }


    public String buttonVolver_action() {    
	this.hiddenField1.setValue("");
	for(Iterator it=this.getSessionManualesViaWebBean().getFail().iterator();it.hasNext();){
	    System.out.println("ELIMINANDO");
	    File temp_=(File)it.next();
	    System.out.println("DELETE PATH:"+temp_.getAbsolutePath());
	    if(temp_.exists()){
		temp_.delete();
	    }
	}        
	this.getSessionManualesViaWebBean().setRenderedAlert(false);
	this.getSessionManualesViaWebBean().setRenderedModificarButton(false);
	this.limpiarCampos();
        return "CONSULTA";
    }
    
    private void limpiarCampos(){
	this.textAreaDesc.setValue("");
	this.dropDownApp.setSelected("Seleccione...");
	this.dropDownVersiones.setSelected("Seleccione...");
	this.hiddenField1.setValue("");
    }
}
